package com.han.methodlog.service.impl;

import com.han.methodlog.config.MailConfig;
import com.han.methodlog.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

@Slf4j
@Service
public class MailServiceImpl implements MailService {

    private final MailConfig mailConfig;

    public MailServiceImpl(MailConfig mailConfig) {
        this.mailConfig = mailConfig;
    }

    @Override
    public void sendMail(String subject, String content) throws MessagingException {

        // 1. 配置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.host", mailConfig.getSmtp().getHost());
        properties.put("mail.smtp.port", mailConfig.getSmtp().getPort());
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.ssl.trust", mailConfig.getSmtp().getHost());
        // 是否进行debug
        properties.put("mail.debug", "true");


        // 2. 创建认证信息
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mailConfig.getUsername(), mailConfig.getPassword());
            }
        };

        // 3. 创建邮件会话
        Session session = Session.getInstance(properties, authenticator);

        // 4. 构建邮件
        Message mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(mailConfig.getUsername()));
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(String.join(",", mailConfig.getTo())));
        mimeMessage.setSubject(subject);
        mimeMessage.setText(content);

        // 5.发送邮件
        Transport.send(mimeMessage);
    }



}
